package com.letoken.platform.repo.wallet.redis;

import com.letoken.platform.pub.constant.RedisKeyConstant;
import com.letoken.platform.pub.enums.TokenTransactionStatusEnum;
import com.letoken.platform.pub.util.BeanUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

/**
 * @author letokenlabs
 * @date 2022/12/19$
 */
public class UserWalletRedisBloomFilter {

    private StringRedisTemplate stringRedisTemplate;


    private UserWalletRedisBloomFilter() {
        stringRedisTemplate = BeanUtil.getBean(StringRedisTemplate.class);
    }

    private enum Singleton {
        INSTANCE;
        private UserWalletRedisBloomFilter instance;

        // JVM会保证此方法绝对只调用一次
        Singleton() {
            instance = new UserWalletRedisBloomFilter();
        }
    }

    public static UserWalletRedisBloomFilter me() {
        return UserWalletRedisBloomFilter.Singleton.INSTANCE.instance;
    }

    public void setTxOrder(String txId, TokenTransactionStatusEnum status, boolean value) {
        if (!StringUtils.isEmpty(txId)) {
            if (status == TokenTransactionStatusEnum.PENDING) {
                stringRedisTemplate.opsForValue().setBit(RedisKeyConstant.BLOOM_USER_WALLET_TX_GOING, txId.hashCode() & Integer.MAX_VALUE, value);
            } else if(status == TokenTransactionStatusEnum.COMPLETED) {
                stringRedisTemplate.opsForValue().setBit(RedisKeyConstant.BLOOM_USER_WALLET_TX_DONE , txId.hashCode() & Integer.MAX_VALUE, value);
            }
        }
    }
    public boolean getTxOrder(String txId, TokenTransactionStatusEnum status) {
        if (!StringUtils.isEmpty(txId)) {
            if (status == TokenTransactionStatusEnum.PENDING) {
                return stringRedisTemplate.opsForValue().getBit(RedisKeyConstant.BLOOM_USER_WALLET_TX_GOING, txId.hashCode() & Integer.MAX_VALUE);
            } else if(status == TokenTransactionStatusEnum.COMPLETED) {
                return stringRedisTemplate.opsForValue().getBit(RedisKeyConstant.BLOOM_USER_WALLET_TX_DONE, txId.hashCode() & Integer.MAX_VALUE);
            }
        }
        return false;
    }

    public void setWithdrawOrder(String sn, boolean value) {
        if (!StringUtils.isEmpty(sn)) {
            stringRedisTemplate.opsForValue().setBit(RedisKeyConstant.BLOOM_USER_WALLET_WITHDRAW, sn.hashCode() & Integer.MAX_VALUE, value);
        }
    }

    public boolean getWithdrawOrder(String sn) {
        if (!StringUtils.isEmpty(sn)) {
            return stringRedisTemplate.opsForValue().getBit(RedisKeyConstant.BLOOM_USER_WALLET_WITHDRAW, sn.hashCode() & Integer.MAX_VALUE);
        }
        return false;
    }
}
